//登录接口
export const userLogin = async (account : string, password : string) => {
	try {
		const res = await fetch('http://localhost:3000/login', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify({ account, password }) 
		})

		const data = await res.json()

		if (data.code === 200) {
			console.log('✅ 登录成功', data.user.account)
			uni.setStorageSync('loginCode', data.user.id)

		} else {
			console.warn('❌ 登录失败:', data.message)
		}

		return data // 返回完整结果，供外部使用
	} catch (err) {
		console.error('请求出错:', err)
		return { code: 500, message: '网络错误' }
	}
}

//注册接口
export const userRegister = async (userData : {
	userName : string,
	account : string,
	password : string,
	headPortrait ?: string
}) => {
	try {
		const res = await fetch('http://localhost:3000/register', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(userData)
		});

		const data = await res.json();
		console.log('注册成功')
		return data; // 返回后由调用方判断是否成功

	} catch (err) {
		console.error('注册请求失败:', err);
		return { code: 500, message: '网络错误' };
	}

}

//添加订单
export const recipient = async (recipientData : {
	trackingNumber : string,
	recipientName : string,
	phoneSuffix : string,
	deliveryAddress : string,
	contactInfo : string,
	remarks : string
}) => {
	try{
		const res = await fetch('http://localhost:3000/orders/add',{
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(recipientData)
		})
		return await res.json()
	}catch(err){
		console.error('订单请求失败:', err);
		return { code: 500, message: '网络错误' };
	}
}

//添加常用地址
export const resses = async (ressesData: {
  userId: string,         // 用户 ID，唯一标识
  tag: string,            // 地址标签，如“家”、“学校”
  address: string,        // 详细地址
  contactName: string,    // 联系人姓名
  contactPhone: string    // 联系人手机号
}) => {
	try {
		const res = await fetch('http://localhost:3000/address/add',{
			method:'POST',
			headers:{
				'Content-Type': 'application/json'
			},
			body:JSON.stringify(ressesData)
		})
		    const data = await res.json()
		    return data
	} catch(err) {
		    console.error('地址添加失败:', err)
		    return { code: 500, message: '网络请求失败' }
	}
}

//通过userid 查询用户地址
export const getAddressList = async (userId: string) => {
  try {
    const res = await fetch(`http://localhost:3000/address/list?userId=${userId}`);
    const data = await res.json();
    return data;
  } catch (err) {
    console.error('获取地址列表失败:', err);
    return { code: 500, message: '网络错误' };
  }
};
//删除地址
export const deleteAddress = async (id: string) => {
  try {
    const res = await fetch(`http://localhost:3000/address/delete/${id}`, {
      method: 'DELETE',
    });
    const data = await res.json();
    return data;
  } catch (err) {
    console.error('删除失败:', err);
    return { code: 500, message: '网络错误' };
  }
};